<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <!-- SPU名称 -->
      <el-form-item label="SPU名称">
        <el-input v-model="spu.spuName" placeholder="SPU名称" />
      </el-form-item>
      <!-- 品牌 -->
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <!-- SPU描述 -->
      <el-form-item label="SPU描述">
        <el-input v-model="spu.description" type="textarea" rows="4" />
      </el-form-item>
      <!-- SPU图片 -->
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="imageList"
          :on-preview="handlePictureCardPreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item label="销售属性">
        <!-- 选择框 -->
        <el-select
          v-model="saleAttrId"
          :placeholder="`还可以选择${unSaleAttr.length}条`"
        >
          <el-option
            v-for="sal in unSaleAttr"
            :key="sal.id"
            :label="sal.name"
            :value="`${sal.id}:${sal.name}`"
          />
        </el-select>
        <!-- 添加销售属性按钮 -->
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!saleAttrId"
          @click="addSaleAttr"
        >添加销售属性</el-button>
        <!-- 表单 -->
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column prop="saleAttrName" label="属性名" width="width" />
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
              >添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 保存、取消 -->
      <el-form-item>
        <el-button type="primary" @click="updateOrAddSPU">保存</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SPUForm',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        'category3Id': '',
        'description': '',
        'spuImageList': [
        ],
        'spuName': '',
        'spuSaleAttrList': [
        ],
        'tmId': ''
      },
      tradeMarkList: [],
      imageList: [],
      saleAttrList: [],
      saleAttrId: '',
      // elm
      inputValue: ''
    }
  },
  computed: {
    unSaleAttr() {
      const res = this.saleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
      return res
    }
  },
  methods: {
    // 取消按钮
    cancelFn() {
      this.$emit('updateStatus', { status: 0 })
      Object.assign(this._data, this.$options.data())
    },
    // 保存按钮
    async  updateOrAddSPU() {
      this.spu.spuImageList = this.imageList.map(item => {
        return {
          imgeName: 'item.name',
          imageUrl: (item.response && item.response.data) || item.url
        }
      })
      try {
        await this.$API.spu.reqAddOrUpdateSpu(this.spu)
        this.$message.success('保存成功')
        this.$emit('updateStatus', { status: 0, leavl: this.spu.id ? 1 : 0 })
        // 清楚数据
        Object.assign(this._data, this.$options.data())
      } catch (error) {
        return
      }
    },
    // 添加销售属性
    addSaleAttr() {
      this.spu.spuSaleAttrList.push({
        baseSaleAttrId: this.saleAttrId.split(':')[0],
        saleAttrName: this.saleAttrId.split(':')[1],
        spuSaleAttrValueList: []
      })
      this.saleAttrId = ''
    },
    // 上传图片
    handleSuccess(response, file, fileList) {
      this.imageList = fileList
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.imageList = fileList
    },
    // 查看图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 点击添加
    showInput(row) {
      this.$set(row, 'inputVisible', true)
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // input框失去焦点
    handleInputConfirm(row) {
      const inputValue = this.inputValue

      // 判断是否为空
      if (inputValue.trim() === '') {
        this.$message.warning('不能为空')
        return
      }
      // 判断是否有重复属性
      const res = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === inputValue
      })
      if (res) {
        this.$message.warning('不能有重复属性')
        return
      }

      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        // saleAttrName: row.saleAttrName,
        saleAttrValueName: inputValue
        // spuId: row.spuId
      })

      row.inputVisible = false
      this.inputValue = ''
    },
    // 获取数据
    async initSpuData(row) {
      row.id ? '' : this.spu.category3Id = row
      try {
        if (row.id) {
        // 获取spu信息
          const res = await this.$API.spu.reqSpu(row.id)
          this.spu = res.data
          // 获取SPU图标的接口
          const res2 = await this.$API.spu.reqSpuImageList(row.id)
          const arrImage = res2.data
          arrImage.forEach(item => {
            item.name = item.imgName
            item.url = item.imgUrl
          })
          this.imageList = arrImage
        }

        // 获取品牌信息
        const res1 = await this.$API.spu.reqTradeMarkList()
        this.tradeMarkList = res1.data

        // 获取平台全部销售属性
        const res3 = await this.$API.spu.reqBaseSaleAttrList()
        this.saleAttrList = res3.data
      } catch (error) {
        console.log(error.message)
      }
    }
  }

}

</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

